<template>
  <div>
    <a-button type="primary" @click="showModal">选择商品</a-button>
    <a-modal
      v-model:visible="data.visible"
      :width="1000"
      title="选择商品"
      @ok="finish"
      @cancel="cancel"
    >
      <div class="model-box" v-if="data.visible">
        <a-table
          :row-selection="rowSelection"
          :pagination="{
            hideOnSinglePage: true,
          }"
          rowKey="ProductID"
          :columns="columns"
          :data-source="data.tableList"
        >
          <template #bodyCell="{ column, text }">
            <template v-if="column.dataIndex === 'name'">
              <a>{{ text }}</a>
            </template>
          </template>
        </a-table>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive } from 'vue';
  import type { TableColumnType } from 'ant-design-vue';
  import { getGoodsList } from './api/index';
  import { notification } from 'ant-design-vue';
  interface DataItem {
    ProductName: string;
    ProductAmount: number;
    ProductUnitPrice: number;
  }
  const emits = defineEmits(['submit']);
  const columns: TableColumnType<DataItem>[] = [
    {
      title: '商品名称',
      dataIndex: 'ProductName',
    },
    {
      title: '数量',
      dataIndex: 'ProductAmount',
    },
    {
      title: '单价',
      dataIndex: 'ProductUnitPrice',
    },
  ];
  const data: {
    visible: boolean;
    tableList: DataItem[];
    selectedRowKeys: string[];
    selectedRows: DataItem[];
  } = reactive({ visible: false, tableList: [], selectedRowKeys: [], selectedRows: [] });

  onMounted(() => {
    data.selectedRowKeys = [];
    data.selectedRows = [];
    data.visible = false;
  });
  async function getList() {
    let res = await getGoodsList();
    data.tableList = res;
  }
  const rowSelection = computed(() => {
    return {
      checkStrictly: true,
      selectedRowKeys: data.selectedRowKeys,
      onChange: (selectedRowKeys: string[], selectedRows: DataItem[]) => {
        data.selectedRowKeys = selectedRowKeys;
        data.selectedRows = selectedRows;
      },
    };
  });

  async function showModal() {
    await getList();
    data.visible = true;
  }
  function finish() {
    console.log('data.selectedRows: ', data.selectedRows);
    if (data.selectedRows.length > 0) {
      emits('submit', data.selectedRows);
      cancel();
    } else {
      notification.error({
        message: '提示',
        description: '请至少选择一个信息',
      }); //提示消息
    }
  }
  function cancel() {
    data.selectedRowKeys = [];
    data.selectedRows = [];
    data.visible = false;
  }
</script>

<style scoped>
  .model-box {
    padding: 20px 30px;
  }
</style>
